package org.gesplan.controller;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.gesplan.entity.Material;
import org.gesplan.entity.MaterialFamily;
import org.gesplan.exceptions.NonexistentEntityException;
import org.gesplan.exceptions.PreexistingEntityException;
import org.gesplan.util.Utils;


/**
 *
 * @author David
 */
public class MaterialJpaController {

    private EntityManagerFactory emf = null;

	
    public MaterialJpaController() {
        this.emf = Utils.getEntityManagerFactory();
    }

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    
    public void create(Material material) throws PreexistingEntityException, Exception {
        
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            MaterialFamily materialFamilyId = material.getMaterialFamilyId();
            if (materialFamilyId != null) {
                materialFamilyId = em.getReference(materialFamilyId.getClass(), materialFamilyId.getId());
                material.setMaterialFamilyId(materialFamilyId);
            }
            em.persist(material);
            if (materialFamilyId != null) {
                materialFamilyId.getMaterialCollection().add(material);
                em.merge(materialFamilyId);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findMaterial(material.getId()) != null) {
                throw new PreexistingEntityException("Material " + material + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }

    
    public void edit(Material material) throws NonexistentEntityException, Exception {
        
        EntityManager em = null;
        String id = material.getId();
        if (findMaterial(id) == null) {
            create(material);
        } else {
            try {
                em = getEntityManager();
                em.getTransaction().begin();
                Material persistentMaterial = em.find(Material.class, material.getId());
                MaterialFamily materialFamilyIdOld = persistentMaterial.getMaterialFamilyId();
                MaterialFamily materialFamilyIdNew = material.getMaterialFamilyId();
                if (materialFamilyIdNew != null) {
                    materialFamilyIdNew = em.getReference(materialFamilyIdNew.getClass(), materialFamilyIdNew.getId());
                    material.setMaterialFamilyId(materialFamilyIdNew);
                }
                material = em.merge(material);
                if (materialFamilyIdOld != null && !materialFamilyIdOld.equals(materialFamilyIdNew)) {
                    materialFamilyIdOld.getMaterialCollection().remove(material);
                    materialFamilyIdOld = em.merge(materialFamilyIdOld);
                }
                if (materialFamilyIdNew != null && !materialFamilyIdNew.equals(materialFamilyIdOld)) {
                    materialFamilyIdNew.getMaterialCollection().add(material);
                    em.merge(materialFamilyIdNew);
                }
                em.getTransaction().commit();
            } catch (Exception ex) {
                String msg = ex.getLocalizedMessage();
                if (msg == null || msg.length() == 0) {
                    if (findMaterial(id) == null) {
                        throw new NonexistentEntityException("The material with id " + id + " no longer exists.");
                    }
                }
                throw ex;
            } finally {
                if (em != null) {
                    em.close();
                }
            }
        }
        
    }

    
    public void destroy(String id) throws NonexistentEntityException, RollbackException {
        
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Material material;
            try {
                material = em.getReference(Material.class, id);
                material.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The material with id " + id + " no longer exists.", enfe);
            }
            MaterialFamily materialFamilyId = material.getMaterialFamilyId();
            if (materialFamilyId != null) {
                materialFamilyId.getMaterialCollection().remove(material);
                em.merge(materialFamilyId);
            }
            em.remove(material);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        
    }

    
    public List<Material> findMaterialEntities() {
        return findMaterialEntities(true, -1, -1);
    }

    public List<Material> findMaterialEntities(int maxResults, int firstResult) {
        return findMaterialEntities(false, maxResults, firstResult);
    }

    
    @SuppressWarnings({ "rawtypes", "unchecked" })    
    private List<Material> findMaterialEntities(boolean all, int maxResults, int firstResult) {
        
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Material.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
        
    }

    
    public Material findMaterial(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Material.class, id);
        } finally {
            em.close();
        }
    }

    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public int getMaterialCount() {
        
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Material> rt = cq.from(Material.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
        
    }

    
}